package com.ruoyi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.project.domain.entity.PhaseDictionary;
import com.ruoyi.project.domain.entity.ProjectAttachment;
import com.ruoyi.project.domain.entity.ProjectCosting;
import com.ruoyi.project.domain.entity.ProjectParticipan;
import com.ruoyi.project.domain.query.ProjectFileQuery;
import com.ruoyi.project.domain.query.ProjectParticipanQuery;
import com.ruoyi.project.mapper.ProjectAttachmentMapper;
import com.ruoyi.project.mapper.ProjectCostingMapper;
import com.ruoyi.project.mapper.ProjectParticipanMapper;
import com.ruoyi.project.service.IPhaseDictionaryService;
import com.ruoyi.project.service.IProjectAttachmentService;
import com.ruoyi.project.service.IProjectParticipanService;
import org.springframework.stereotype.Service;
import shade.io.netty.handler.codec.http.multipart.FileUpload;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;


@Service
public class ProjectAttachmentServiceImpl extends ServiceImpl<ProjectAttachmentMapper, ProjectAttachment> implements IProjectAttachmentService {

    @Resource
    private ProjectAttachmentMapper projectAttachmentMapper;

    @Resource
    private ProjectCostingMapper costingMapper;

    @Resource
    private IPhaseDictionaryService dictionaryService;


    //分页
    @Override
    public TableDataInfo getPage(ProjectFileQuery query) {
        Page<Object> page = PageHelper.startPage(query.getPageNum(),query.getPageSize());
        List<ProjectAttachment> list = projectAttachmentMapper.getList(query);
        return new TableDataInfo(list, page.getTotal());
    }

    //新增
    @Override
    public Boolean addInfo(ProjectAttachment project) {
        if (project.getAttachmentType().equals("5") || project.getAttachmentType().equals("22")){//正式清单只能上传一个？先删除
//            QueryWrapper<ProjectAttachment> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("attachment_type", project.getAttachmentType());
//            queryWrapper.eq("project_no", project.getProjectNo());
            projectAttachmentMapper.deleteHistory(project.getProjectNo(),project.getAttachmentType());
        }
        project.setOperator(SecurityUtils.getLoginUser().getUser().getNickName());
        setFileName(project);

        Long phaseId = project.getPhaseId();

        //销售项目不需要设置环节信息
        if ("99".equals(String.valueOf(phaseId))){
            return this.save(project);
        }

        if (phaseId == null) {
            throw new RuntimeException("后端接口异常");
        }
        PhaseDictionary byId = dictionaryService.getById(project.getPhaseId());
        project.setPhaseName(byId.getPhaseName());

        return this.save(project);
    }

    @Override
    public Boolean updateInfo(ProjectAttachment project) {
        project.setOperator(SecurityUtils.getLoginUser().getUser().getNickName());
        if (project.getAttachmentType().equals("5") || project.getAttachmentType().equals("22")){//正式清单只能上传一个先删除再新增
//            QueryWrapper<ProjectAttachment> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("attachment_type", project.getAttachmentType());
//            queryWrapper.eq("project_no", project.getProjectNo());
            projectAttachmentMapper.deleteHistory(project.getProjectNo(),project.getAttachmentType());
            return this.saveOrUpdate(project);
        }
        setFileName(project);
        return this.updateById(project);
    }

    @Override
    public Boolean deleteInfo(String id) {
        ProjectAttachment fileInfo = this.getInfoById(id);

        //如果删除的是正式清单 上传的excel内容也要删除
        if (fileInfo.getAttachmentType().equals("5")){
            costingMapper.deleteByProjectNo(fileInfo.getProjectNo());
        }

        return this.removeById(id);
    }

    @Override
    public ProjectAttachment getInfoById(String id) {
        return this.getById(id);
    }

    @Override
    public List<ProjectAttachment> getList(ProjectFileQuery query) {
        LambdaQueryWrapper<ProjectAttachment> wrapper = new QueryWrapper<ProjectAttachment>().lambda()
                .eq(query.getProjectNo()!=null,ProjectAttachment::getProjectNo,query.getProjectNo())
                .eq(query.getPhaseId()!=null,ProjectAttachment::getPhaseId,query.getPhaseId());
        return this.list(wrapper);
    }

    public void setFileName(ProjectAttachment project) {
        String filePaths = project.getFilePath();
        // 按逗号分隔字符串
        String fileName = "";
        try {
            if (StringUtils.isNotEmpty(filePaths) && filePaths.contains(",")) {
                String[] paths = filePaths.split(",");
                // 遍历每个路径并提取基础文件名
                String[] baseFileNames = new String[paths.length];
                for (int i = 0; i < paths.length; i++) {
                    String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath(), paths[i]);
                    String name = FileUtils.getName(pathFileName);
                    // 去掉时间戳部分（假设文件名与时间戳之间用"_"分隔）
                    String nameSuffix = name.lastIndexOf("_") != -1 ? name.substring(0, name.lastIndexOf("_")) : name;
                    // 提取文件扩展名
                    String extend = "";
                    if (name != null && name.contains(".")) {
                        extend = name.substring(name.lastIndexOf("."));
                    }
                    fileName = fileName + nameSuffix + extend + ",";
                }

            }else{
                if (StringUtils.isNotEmpty(filePaths)){
                    String pathFileName = null;

                    pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath(),filePaths);
                    String name = FileUtils.getName(pathFileName);
                    // 去掉时间戳部分（假设文件名与时间戳之间用"_"分隔）
                    String nameSuffix = name.lastIndexOf("_") != -1 ? name.substring(0, name.lastIndexOf("_")) : name;
                    // 提取文件扩展名
                    String extend = "";
                    if (name != null && name.contains(".")) {
                        extend = name.substring(name.lastIndexOf("."));
                    }
                    fileName = fileName + nameSuffix + extend + ",";
                }
                String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath(),filePaths);
                System.out.println("pathFileName:" + pathFileName);
            }
        } catch (IOException e) {
            throw new RuntimeException("文件保存失败,请检查规范文件名称");
        }
        if (StringUtils.isNotEmpty(fileName)) {
            project.setFileName(fileName.substring(0, fileName.length() - 1));
        }else {
            project.setFileName("");
        }
    }

}
